<!-- eslint-disable unused-imports/no-unused-vars -->
<script setup lang="ts">
import type { FormRules } from "element-plus"
import type { CreateOrUpdateEnterpriseRequest, EnterpriseInfo, EnterpriseQuery } from "./apis/type"
import { usePagination } from "@@/composables/usePagination"
import { CirclePlus, RefreshRight, Search, Upload } from "@element-plus/icons-vue"
import { cloneDeep } from "lodash-es"
import {
  checkEnterpriseNameApi,
  createEnterpriseApi,
  getEnterpriseListApi,
  updateEnterpriseApi,
  updateEnterpriseStatusApi,
  uploadLicenseApi
} from "./apis/enterprise"

// 常量定义
const INDUSTRY_TYPE_OPTIONS = [
  { label: "互联网", value: "internet" },
  { label: "金融", value: "finance" },
  { label: "制造业", value: "manufacturing" },
  { label: "教育培训", value: "education" },
  { label: "其他", value: "other" }
]

const SCALE_OPTIONS = [
  { label: "50人以下", value: "small" },
  { label: "50-100人", value: "medium-small" },
  { label: "100-500人", value: "medium" },
  { label: "500-1000人", value: "medium-large" },
  { label: "1000人以上", value: "large" }
]

// 响应式数据
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const enterpriseList = ref<EnterpriseInfo[]>([])

// 搜索表单
const searchFormRef = useTemplateRef("searchFormRef")
const searchData = reactive<Partial<Pick<EnterpriseQuery, "fullName" | "industryType">>>({
  fullName: "",
  industryType: ""
})

// 编辑表单
const dialogVisible = ref<boolean>(false)
const formRef = useTemplateRef("formRef")
const DEFAULT_FORM_DATA: CreateOrUpdateEnterpriseRequest = {
  id: undefined,
  fullName: "",
  shortName: "",
  industryType: "internet",
  scale: "small",
  address: "",
  contactName: "",
  contactPhone: "",
  contactEmail: "",
  licenseUrl: "",
  introduction: "",
  status: true
}
const formData = ref<CreateOrUpdateEnterpriseRequest>(cloneDeep(DEFAULT_FORM_DATA))

// 表单验证规则
const formRules: FormRules<CreateOrUpdateEnterpriseRequest> = {
  fullName: [
    { required: true, trigger: "blur", message: "请输入企业全称" },
    { min: 2, max: 100, trigger: "blur", message: "企业全称长度应为2-100个字符" },
    {
      validator: (rule, value, callback) => {
        if (!value) return callback()
        checkEnterpriseNameApi(value, formData.value.id)
          .then(({ data }) => {
            if (data.exist) {
              callback(new Error("企业名称已存在"))
            } else {
              callback()
            }
          })
          .catch(() => {
            callback(new Error("检查失败，请稍后重试"))
          })
      },
      trigger: "blur"
    }
  ],
  shortName: [
    { required: true, trigger: "blur", message: "请输入企业简称" },
    { min: 1, max: 20, trigger: "blur", message: "企业简称长度应为1-20个字符" }
  ],
  industryType: [{ required: true, trigger: "change", message: "请选择行业类型" }],
  scale: [{ required: true, trigger: "change", message: "请选择企业规模" }],
  address: [{ required: true, trigger: "blur", message: "请输入企业地址" }],
  contactName: [{ required: true, trigger: "blur", message: "请输入联系人姓名" }],
  contactPhone: [
    { required: true, trigger: "blur", message: "请输入联系电话" },
    { pattern: /^1[3-9]\d{9}$/, trigger: "blur", message: "请输入正确的手机号格式" }
  ],
  contactEmail: [
    { required: true, trigger: "blur", message: "请输入联系邮箱" },
    { type: "email", trigger: "blur", message: "请输入正确的邮箱格式" }
  ]
}

// 方法定义
async function getEnterpriseList() {
  loading.value = true
  try {
    const { data } = await getEnterpriseListApi({
      currentPage: paginationData.currentPage,
      size: paginationData.pageSize,
      ...searchData
    })
    paginationData.total = data.total
    enterpriseList.value = data.list
  } catch (_error) {
    ElMessage.error("获取企业列表失败")
    enterpriseList.value = []
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  paginationData.currentPage = 1
  getEnterpriseList()
}

function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
}

function openAddDialog() {
  resetForm()
  dialogVisible.value = true
}

function openEditDialog(enterprise: EnterpriseInfo) {
  formData.value = cloneDeep(enterprise)
  dialogVisible.value = true
}

function resetForm() {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

async function handleSave() {
  await formRef.value?.validate()
  loading.value = true
  try {
    const api = formData.value.id ? updateEnterpriseApi : createEnterpriseApi
    await api(formData.value)
    ElMessage.success(formData.value.id ? "更新成功" : "创建成功")
    dialogVisible.value = false
    getEnterpriseList()
  } catch (error) {
    ElMessage.error(formData.value.id ? "更新失败" : "创建失败")
  } finally {
    loading.value = false
  }
}

async function handleStatusChange(id: number, currentStatus: boolean) {
  const newStatus = !currentStatus
  try {
    await updateEnterpriseStatusApi(id, newStatus)
    ElMessage.success(newStatus ? "启用成功" : "禁用成功")
    getEnterpriseList()
  } catch (error) {
    ElMessage.error(newStatus ? "启用失败" : "禁用失败")
  }
}

async function handleUploadLicense(file: File) {
  // 检查文件大小
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error("文件大小不能超过10MB")
    return false
  }
  // 检查文件类型
  const validTypes = ["image/jpeg", "image/jpg", "application/pdf"]
  if (!validTypes.includes(file.type)) {
    ElMessage.error("只支持JPG、PDF格式的文件")
    return false
  }

  try {
    const { data } = await uploadLicenseApi(file)
    formData.value.licenseUrl = data.url
    ElMessage.success("上传成功")
    return true
  } catch (error) {
    ElMessage.error("上传失败，请稍后重试")
    return false
  }
}

// 监听分页变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getEnterpriseList)

// 初始化数据
onMounted(() => {
  getEnterpriseList()
})
</script>

<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="fullName" label="企业全称">
          <el-input v-model="searchData.fullName" placeholder="请输入企业全称" />
        </el-form-item>
        <el-form-item prop="industryType" label="行业类型">
          <el-select v-model="searchData.industryType" placeholder="请选择" clearable style="width: 120px;">
            <el-option
              v-for="item in INDUSTRY_TYPE_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="RefreshRight" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作和表格区域 -->
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <el-button type="primary" :icon="CirclePlus" @click="openAddDialog">
          添加企业
        </el-button>
      </div>

      <el-table :data="enterpriseList" style="width: 100%">
        <el-table-column prop="fullName" label="企业全称" width="200" />
        <el-table-column prop="shortName" label="企业简称" width="120" />
        <el-table-column prop="industryType" label="行业类型" width="100">
          <template #default="scope">
            <el-tag>
              {{ INDUSTRY_TYPE_OPTIONS.find(item => item.value === scope.row.industryType)?.label || scope.row.industryType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="scale" label="企业规模" width="120">
          <template #default="scope">
            <el-tag>
              {{ SCALE_OPTIONS.find(item => item.value === scope.row.scale)?.label || scope.row.scale }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="企业地址" show-overflow-tooltip />
        <el-table-column prop="contactName" label="联系人" width="100" />
        <el-table-column prop="contactPhone" label="联系电话" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              @change="handleStatusChange(scope.row.id!, scope.row.status)"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column fixed="right" label="操作" width="120" align="center">
          <template #default="scope">
            <el-button type="primary" text @click="openEditDialog(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :current-page="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id ? '编辑企业' : '添加企业'"
      width="60%"
      @closed="resetForm"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item prop="fullName" label="企业全称">
          <el-input v-model="formData.fullName" placeholder="请输入企业全称" />
        </el-form-item>
        <el-form-item prop="shortName" label="企业简称">
          <el-input v-model="formData.shortName" placeholder="请输入企业简称" />
        </el-form-item>
        <el-form-item prop="industryType" label="行业类型">
          <el-select v-model="formData.industryType" placeholder="请选择">
            <el-option
              v-for="item in INDUSTRY_TYPE_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="scale" label="企业规模">
          <el-select v-model="formData.scale" placeholder="请选择">
            <el-option
              v-for="item in SCALE_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="address" label="企业地址">
          <el-input v-model="formData.address" placeholder="请输入企业地址" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item prop="contactName" label="联系人姓名">
          <el-input v-model="formData.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item prop="contactPhone" label="联系电话">
          <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item prop="contactEmail" label="联系邮箱">
          <el-input v-model="formData.contactEmail" placeholder="请输入联系邮箱" />
        </el-form-item>
        <el-form-item label="营业执照">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="() => {}"
            :before-upload="handleUploadLicense"
            action=""
            :auto-upload="false"
          >
            <img v-if="formData.licenseUrl" :src="formData.licenseUrl" class="avatar">
            <el-icon v-else class="avatar-uploader-icon">
              <Upload />
            </el-icon>
          </el-upload>
          <div class="upload-tip">
            支持JPG、PDF格式，大小不超过10MB
          </div>
        </el-form-item>
        <el-form-item prop="introduction" label="企业简介">
          <el-input v-model="formData.introduction" placeholder="请输入企业简介" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="loading" @click="handleSave">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
}

.toolbar-wrapper {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.pager-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  background-color: #f0f2f5;
  overflow: hidden;
}

.upload-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}
</style>
